package org.web.demo.dao.impl;

import org.web.demo.common.qo.QueryObject;
import org.web.demo.common.util.MyBatisUtil;
import org.web.demo.dao.IUserDAO;
import org.web.demo.entity.User;
import org.apache.ibatis.session.SqlSession;

import java.util.List;


/**
 * @author yexi
 */
public class UserDAOImpl implements IUserDAO {

    private final String PREFIX = "org.web.demo.dao.IUserDAO.";

    @Override
    public void insert(User u) {
        try {
            SqlSession session = MyBatisUtil.openSession();
            session.insert(PREFIX + "insert", u);
            session.commit();//提交事务
            session.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void update(User u) {
        SqlSession session = MyBatisUtil.openSession();
        session.update(PREFIX + "update", u);
        session.commit();
        session.close();
    }

    @Override
    public void delete(long id) {
        SqlSession session = MyBatisUtil.openSession();
        session.delete(PREFIX + "delete", id);
        session.commit();
        session.close();
    }

    @Override
    public User selectOne(long id) {
        User u = null;
        SqlSession session = MyBatisUtil.openSession();
        u = session.selectOne(PREFIX + "selectOne", id);
        session.close();
        return u;
    }

    @Override
    public List<User> selectAll() {
        List<User> users = null;
        SqlSession session = MyBatisUtil.openSession();
        users = session.selectList(PREFIX + "selectAll");
        session.close();
        return users;
    }

    @Override
    public int selectCount(QueryObject qo) {
        SqlSession sqlsession = MyBatisUtil.openSession();
        int a = sqlsession.selectOne(PREFIX + "selectCount", qo);
        sqlsession.close();
        return a;
    }

    @Override
    public List<User> query(QueryObject qo) {
        List<User> users = null;
        SqlSession session = MyBatisUtil.openSession();
        users = session.selectList(PREFIX + "query", qo);
        session.close();
        return users;
    }

    @Override
    public User checkUser(String username) {
        SqlSession session = MyBatisUtil.openSession();
        User u = session.selectOne(PREFIX + "checkUser", username);
        session.close();
        return u;
    }
}